import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import csv

# 整合的弱口令数据（按设备类型分类）
WEAK_PASSWORD_DATA = {
    # 1. 华为安全产品
    "华为安全产品": [
        {"产品": "AntiDDoS1500(V100R001)", "类型": "BootROM", "账号": "-", "密码": "O&m15213"},
        {"产品": "AntiDDoS1500(V100R001)", "类型": "Console/Web/Telnet", "账号": "admin", "密码": "Admin@123"},
        {"产品": "AntiDDoS8000(V100R001)", "类型": "BootROM", "账号": "-", "密码": "WWW@HUAWEI"},
        {"产品": "AntiDDoS8000(V100R001)", "类型": "Console/Web/Telnet", "账号": "admin", "密码": "Admin@123"},
        {"产品": "ASG2000(V100R001)", "类型": "BootROM", "账号": "-", "密码": "O&m15213"},
        {"产品": "ASG2000(V100R001)", "类型": "Console/Web", "账号": "admin", "密码": "Admin@123"},
        {"产品": "Eudemon 100E/200S(V200R001C03)", "类型": "BootROM", "账号": "-", "密码": "8060"},
        {"产品": "Eudemon 100E/200S(V200R001C03)", "类型": "Console", "账号": "eudemon", "密码": "eudemon"},
        {"产品": "Eudemon 100E/200S(V200R001C03)", "类型": "Console", "账号": "admin", "密码": "Admin@123"},
        {"产品": "USG2100(V100R001-V100R005)", "类型": "BootROM", "账号": "-", "密码": "O&m15213"},
        {"产品": "USG2100(V100R001-V100R005)", "类型": "Console/Web", "账号": "admin", "密码": "Admin@123"},
        {"产品": "USG9500(V200R001/V300R001)", "类型": "BootROM", "账号": "-", "密码": "WWW@HUAWEI"},
        {"产品": "USG9500(V200R001/V300R001)", "类型": "Console/Web/Telnet", "账号": "admin", "密码": "Admin@123"},
        {"产品": "NIP200/1000(V100R001)", "类型": "Console", "账号": "admin", "密码": "admin"},
        {"产品": "NIP200/1000(V100R001)", "类型": "Web", "账号": "administrator", "密码": "huawei123"},
        {"产品": "SVN3000(V100R002)", "类型": "BootROM", "账号": "-", "密码": "svn3000;huawei_svn3000;O&m15213"},
        {"产品": "SVN3000(V100R002)", "类型": "Console", "账号": "admin", "密码": "Admin@123"},
    ],
    # 2. 常见IT系统
    "常见IT系统": [
        {"产品": "xxl-job", "类型": "系统登录", "账号": "admin", "密码": "123456"},
        {"产品": "druid", "类型": "系统登录", "账号": "admin", "密码": "123456"},
        {"产品": "druid", "类型": "系统登录", "账号": "admin", "密码": "admin"},
        {"产品": "druid", "类型": "系统登录", "账号": "druid", "密码": "druid123456"},
        {"产品": "nacos", "类型": "系统登录", "账号": "nacos", "密码": "nacos"},
        {"产品": "grafana", "类型": "系统登录", "账号": "admin", "密码": "123456"},
        {"产品": "grafana", "类型": "系统登录", "账号": "admin", "密码": "admin123"},
        {"产品": "zabbix", "类型": "系统登录", "账号": "Admin", "密码": "zabbix"},
        {"产品": "minio", "类型": "系统登录", "账号": "minioadmin", "密码": "minioadmin"},
        {"产品": "minio", "类型": "系统登录", "账号": "minioadmin", "密码": "minio@123"},
        {"产品": "RabbitMQ", "类型": "系统登录", "账号": "guest", "密码": "guest"},
        {"产品": "tomcat", "类型": "系统登录", "账号": "tomcat", "密码": "tomcat"},
        {"产品": "若依框架", "类型": "系统登录", "账号": "admin", "密码": "123456"},
        {"产品": "若依框架", "类型": "系统登录", "账号": "ry", "密码": "123456"},
        {"产品": "致远OA", "类型": "系统登录", "账号": "audit-admin", "密码": "seeyon123456"},
        {"产品": "泛微OA", "类型": "系统登录", "账号": "sysadmin", "密码": "Weaver@2025"},
        {"产品": "海康威视IP摄像机", "类型": "设备登录", "账号": "admin", "密码": "12345"},
    ],
    # 3. 路由器设备
    "路由器设备": [
        {"产品": "全向QL1680", "类型": "Web登录", "账号": "admin", "密码": "qxcomm1680"},
        {"产品": "全向QL1880", "类型": "Web登录", "账号": "root", "密码": "root"},
        {"产品": "TP-LINK TD-8800", "类型": "Web登录", "账号": "admin", "密码": "admin"},
        {"产品": "合勤zyxel642", "类型": "Telnet登录", "账号": "-", "密码": "1234"},
        {"产品": "华为SmartAX MT800", "类型": "Web登录", "账号": "admin", "密码": "admin"},
        {"产品": "伊泰克路由器", "类型": "Web登录", "账号": "supervisor", "密码": "12345"},
        {"产品": "华硕路由器", "类型": "Web登录", "账号": "adsl", "密码": "adsl1234"},
        {"产品": "神州数码6010RA", "类型": "Web登录", "账号": "ADSL", "密码": "ADSL1234"},
        {"产品": "大亚DB102", "类型": "Web登录", "账号": "admin", "密码": "dare"},
        {"产品": "实达ADSL2110-EH", "类型": "Web登录", "账号": "admin", "密码": "starnetadsl"},
    ],
    # 4. 主流安全设备
    "主流安全设备": [
        {"产品": "深信服AF(NGAF V2.2)", "类型": "设备登录", "账号": "admin", "密码": "sangfor"},
        {"产品": "深信服NGAF(V4.3)", "类型": "设备登录", "账号": "admin", "密码": "admin"},
        {"产品": "深信服VPN", "类型": "设备登录", "账号": "Admin", "密码": "Admin"},
        {"产品": "网御漏洞扫描系统", "类型": "设备登录", "账号": "leadsec", "密码": "leadsec"},
        {"产品": "天阗IDS(V7.0)", "类型": "设备登录", "账号": "Admin", "密码": "venus70"},
        {"产品": "联想网御防火墙", "类型": "设备登录", "账号": "administrator", "密码": "administrator"},
        {"产品": "H3C SecPath系列", "类型": "设备登录", "账号": "admin", "密码": "admin"},
        {"产品": "H3C ER3100", "类型": "设备登录", "账号": "admin", "密码": "adminer3100"},
        {"产品": "360天擎", "类型": "设备登录", "账号": "admin", "密码": "admin"},
        {"产品": "天融信NGFW4000", "类型": "设备登录", "账号": "superman", "密码": "talent"},
        {"产品": "山石网科防火墙", "类型": "设备登录", "账号": "hillstone", "密码": "hillstone"},
        {"产品": "飞塔防火墙", "类型": "设备登录", "账号": "admin", "密码": "空密码"},
        {"产品": "Juniper SSG-5", "类型": "设备登录", "账号": "netscreen", "密码": "netscreen"},
    ]
}

class WeakPasswordChecker:
    def __init__(self, root):
        self.root = root
        self.root.title("信安西部-明镜高悬实验室-弱口令检索工具(WeakpassSearcher(v1.0))")
        self.root.geometry("1000x600")
        self.root.resizable(True, True)

        # 筛选条件变量
        self.device_type_var = tk.StringVar()
        self.product_name_var = tk.StringVar()
        self.input_account_var = tk.StringVar()
        self.input_password_var = tk.StringVar()

        # 初始化界面
        self.create_widgets()

    def create_widgets(self):
        # 1. 筛选区域（顶部框架）
        filter_frame = ttk.LabelFrame(self.root, text="筛选条件", padding=(10, 5))
        filter_frame.pack(fill=tk.X, padx=10, pady=5)

        # 设备类型下拉框
        ttk.Label(filter_frame, text="设备类型:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
        device_type_combo = ttk.Combobox(
            filter_frame,
            textvariable=self.device_type_var,
            values=["全部"] + list(WEAK_PASSWORD_DATA.keys()),
            state="readonly"
        )
        device_type_combo.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)
        device_type_combo.current(0)  # 默认选择"全部"

        # 产品名称输入框
        ttk.Label(filter_frame, text="产品名称:").grid(row=0, column=2, padx=5, pady=5, sticky=tk.W)
        product_name_entry = ttk.Entry(filter_frame, textvariable=self.product_name_var, width=30)
        product_name_entry.grid(row=0, column=3, padx=5, pady=5, sticky=tk.W)

        # 搜索按钮
        search_btn = ttk.Button(filter_frame, text="搜索", command=self.search_data)
        search_btn.grid(row=0, column=4, padx=5, pady=5, sticky=tk.W)

        # 2. 口令验证区域（中间框架）
        check_frame = ttk.LabelFrame(self.root, text="口令验证", padding=(10, 5))
        check_frame.pack(fill=tk.X, padx=10, pady=5)

        ttk.Label(check_frame, text="输入账号:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
        account_entry = ttk.Entry(check_frame, textvariable=self.input_account_var, width=20)
        account_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)

        ttk.Label(check_frame, text="输入密码:").grid(row=0, column=2, padx=5, pady=5, sticky=tk.W)
        password_entry = ttk.Entry(check_frame, textvariable=self.input_password_var, show="*", width=20)
        password_entry.grid(row=0, column=3, padx=5, pady=5, sticky=tk.W)

        check_btn = ttk.Button(check_frame, text="验证弱口令", command=self.check_password)
        check_btn.grid(row=0, column=4, padx=5, pady=5, sticky=tk.W)

        # 3. 结果显示区域（中间表格）
        result_frame = ttk.LabelFrame(self.root, text="弱口令数据列表", padding=(10, 5))
        result_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 表格配置
        columns = ("产品", "类型", "账号", "密码")
        self.tree = ttk.Treeview(result_frame, columns=columns, show="headings", selectmode="browse")
        
        # 定义列宽和标题
        self.tree.heading("产品", text="产品名称", anchor=tk.CENTER)
        self.tree.heading("类型", text="登录类型", anchor=tk.CENTER)
        self.tree.heading("账号", text="默认账号", anchor=tk.CENTER)
        self.tree.heading("密码", text="默认密码", anchor=tk.CENTER)
        
        self.tree.column("产品", width=300, anchor=tk.CENTER)
        self.tree.column("类型", width=150, anchor=tk.CENTER)
        self.tree.column("账号", width=150, anchor=tk.CENTER)
        self.tree.column("密码", width=150, anchor=tk.CENTER)

        # 滚动条
        scrollbar_y = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.tree.yview)
        scrollbar_x = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL, command=self.tree.xview)
        self.tree.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)

        # 布局表格和滚动条
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
        scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)

        # 4. 操作按钮区域（底部）
        btn_frame = ttk.Frame(self.root, padding=(10, 5))
        btn_frame.pack(fill=tk.X, padx=10, pady=5)

        export_btn = ttk.Button(btn_frame, text="导出数据", command=self.export_data)
        export_btn.pack(side=tk.LEFT, padx=5)

        refresh_btn = ttk.Button(btn_frame, text="刷新列表", command=self.refresh_data)
        refresh_btn.pack(side=tk.LEFT, padx=5)

        # 初始加载全部数据
        self.refresh_data()

    def get_filtered_data(self):
        """根据筛选条件获取数据"""
        selected_type = self.device_type_var.get()
        product_keyword = self.product_name_var.get().lower()
        filtered_data = []

        # 遍历所有设备类型
        for dev_type, dev_list in WEAK_PASSWORD_DATA.items():
            # 筛选设备类型（全部/指定类型）
            if selected_type != "全部" and dev_type != selected_type:
                continue
            # 筛选产品名称（关键词匹配）
            for item in dev_list:
                if product_keyword in item["产品"].lower():
                    filtered_data.append(item)
        return filtered_data

    def refresh_data(self):
        """刷新表格数据"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        # 加载全部数据
        all_data = []
        for dev_list in WEAK_PASSWORD_DATA.values():
            all_data.extend(dev_list)
        # 插入表格
        for idx, item in enumerate(all_data, 1):
            self.tree.insert(
                "",
                tk.END,
                values=(item["产品"], item["类型"], item["账号"], item["密码"])
            )

    def search_data(self):
        """搜索筛选数据"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        # 获取筛选后的数据
        filtered_data = self.get_filtered_data()
        # 插入表格
        if not filtered_data:
            messagebox.showinfo("提示", "未找到匹配的弱口令数据")
            return
        for idx, item in enumerate(filtered_data, 1):
            self.tree.insert(
                "",
                tk.END,
                values=(item["产品"], item["类型"], item["账号"], item["密码"])
            )

    def check_password(self):
        """验证输入的账号密码是否为弱口令"""
        input_account = self.input_account_var.get().strip()
        input_password = self.input_password_var.get().strip()

        if not input_account or not input_password:
            messagebox.showwarning("警告", "请输入账号和密码")
            return

        # 遍历所有弱口令数据匹配
        matched = []
        for dev_list in WEAK_PASSWORD_DATA.values():
            for item in dev_list:
                # 账号密码完全匹配（忽略大小写）
                if (item["账号"].lower() == input_account.lower() and 
                    item["密码"].lower() == input_password.lower()):
                    matched.append(item)

        if matched:
            result_msg = f"⚠️  检测到弱口令！匹配到以下设备：\n"
            for idx, item in enumerate(matched, 1):
                result_msg += f"{idx}. 产品：{item['产品']} | 类型：{item['类型']}\n"
            messagebox.showwarning("弱口令警告", result_msg)
        else:
            messagebox.showinfo("验证结果", "✅ 未检测到弱口令（或不在已知弱口令库中）")

    def export_data(self):
        """导出当前表格数据为CSV文件"""
        # 获取当前表格数据
        current_items = self.tree.get_children()
        if not current_items:
            messagebox.showwarning("警告", "无数据可导出")
            return

        # 选择保存路径
        file_path = filedialog.asksaveasfilename(
            defaultextension=".csv",
            filetypes=[("CSV文件", "*.csv"), ("所有文件", "*.*")],
            title="导出弱口令数据"
        )
        if not file_path:
            return

        # 写入CSV文件
        try:
            with open(file_path, mode="w", encoding="utf-8-sig", newline="") as f:
                writer = csv.writer(f)
                # 写入表头
                writer.writerow(["产品名称", "登录类型", "默认账号", "默认密码"])
                # 写入数据
                for item in current_items:
                    values = self.tree.item(item, "values")
                    writer.writerow(values)
            messagebox.showinfo("成功", f"数据已导出至：\n{file_path}")
        except Exception as e:
            messagebox.showerror("错误", f"导出失败：{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = WeakPasswordChecker(root)
    root.mainloop()
